<script lang="ts" setup>
import { generatePoints, getMap, translate } from "@/utils";
import * as mars3d from "mars3d";
import { Cartesian3 } from "mars3d-cesium";
import { onMounted, onUnmounted } from "vue";

let map: mars3d.Map | null;
let layer: mars3d.layer.GraphicLayer;

/** 构建地图 */
function createMap() {
  map = getMap("container");

  /** 添加绘画图层 */
  layer = new mars3d.layer.GraphicLayer();
  map.addLayer(layer);
}

/** 球切面平移测试 */
function tryTranslate() {
  const c = Cartesian3.fromDegrees(121.811, 23.5, 1000);

  const px = translate(c, new Cartesian3(10000, 0, 0));
  const py = translate(c, new Cartesian3(0, 10000, 0));
  const pz = translate(c, new Cartesian3(0, 0, 10000));

  drawLine([c, px], "#0000ff");
  drawLine([c, py], "#00ff00");
  drawLine([c, pz], "#ff0000");
  drawPoint(px, "#0000ff", "X");
  drawPoint(py, "#00ff00", "Y");
  drawPoint(pz, "#ff0000", "Z");
}

/** 球面点测试 */
function createPointBall() {
  const center = Cartesian3.fromDegrees(121.311, 23.5, 2500);
  const top = Cartesian3.fromDegrees(121.311, 23.5, 2500 + 25000);

  drawPoint(center, "#ff0000");
  drawPoint(top, "#ff0000");
  drawLine([center, top]);
  drawSphere(center, 25000);

  const points = generatePoints(center, 25000, 1000);
  for (const point of points) {
    drawPoint(point);
  }
}

function drawPoint(position: Cartesian3, color: string = "#00ff00", text: string = "") {
  const graphic = new mars3d.graphic.PointPrimitive({
    position,
    style: { color, pixelSize: 3, label: { text } },
  });
  layer.addGraphic(graphic);
}

function drawLine(positions: Cartesian3[], color: string = "#00ffff") {
  const graphic = new mars3d.graphic.PolylineEntity({
    positions,
    style: { width: 1, color, depthFail: true, depthFailColor: "#ff0000", depthFailOpacity: 0.2 },
  });
  layer.addGraphic(graphic);
}

function drawSphere(position: Cartesian3, radius: number, color: string = "#ffff0080") {
  const graphic = new mars3d.graphic.EllipsoidEntity({
    position,
    style: {
      radii: radius,
      maximumConeDegree: 180,
      materialType: mars3d.MaterialType.EllipsoidElectric,
      materialOptions: {
        color: color,
        speed: 5.0,
      },
      outline: false,
    },
  });
  layer.addGraphic(graphic);
}

onMounted(() => {
  createMap();
  createPointBall();
  tryTranslate();
});

onUnmounted(() => {
  map = null;
});
</script>

<template>
  <div id="container"></div>
</template>

<style lang="scss" scoped>
#container {
  width: 100%;
  height: 100%;
}
</style>
